<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="生成许可证"
    @ok="handleSubmit"
    width="30%"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form';
import { FormSchema } from '/@/components/Table';
import { generateLicense, saveOrUpdate } from '@/views/license/License.api';
import { message } from 'ant-design-vue';
// 表单配置
const formSchema: FormSchema[] = [
  {
    label: 'machineCode',
    field: 'machineCode',
    component: 'InputTextArea',
    rules: [
      {
        required: true,
        message: 'machineCode不能为空',
      },
    ],
    componentProps: {
      placeholder: '请输入机器码',
      autoSize: { minRows: 6, maxRows: 100 }, // 自动调整高度
      style: 'width: 100%', // 宽度占满
    },
  },
];

// 注册表单和弹窗
const [registerForm, { validate }] = useForm({
  labelWidth: 120,
  schemas: formSchema,
  showActionButtonGroup: false,
});
const isUpdate = ref(false);
const record = ref({});
const [registerModal, { closeModal }] = useModalInner((data) => {
  isUpdate.value = data?.isUpdate;
  record.value = data.record;
});

const emit = defineEmits([ 'success']);
const errorMessage = ref('');
// 提交处理
async function handleSubmit() {
  try {
    const values = await validate();
    console.log("values",values)
    // await saveOrUpdate(values, isUpdate.value);
    let machineCode = values.machineCode;
    if (machineCode) {
      try {
        const params = {...record.value, machineCode};
        await generateLicense(params);
        // message.success('许可证生成成功');
      } catch (error) {
        console.log("error",error)
        // errorMessage.value = '许可证生成失败:'+ error.message;
        // message.error(errorMessage.value);
      }
    } else {
      message.warning('machineCode 不能为空');
    }
    closeModal();
    emit('success', { isUpdate: isUpdate.value, values })
  } catch (error) {
    console.error('表单验证失败', error);
  }
}
</script>
